import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
//引入router路由
import router from './router'
//引入icon图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import './assets/less/index.less'
//引入vuex
import store from './store/index.js'
//引入mock
import './api/mock.js'

import api from './api/api.js'
import home from './api/mockData/home'

//完整引入ElementPlus
// import ElementPlus from 'element-plus'
// import 'element-plus/dist/index.css'

//引入icon图标
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
// app.use(ElementPlus)
app.config.globalProperties.$api = api

store.commit('addMenu', router)

function checkRouter(path) {
  let hasCheck = router.getRoutes().filter(router => router.path == path).length
  if (hasCheck) {
    return true
  } else {
    return false
  }
}
//全局前置路由守卫
router.beforeEach((to, from, next) => {
  store.commit('getToken')
  const token = store.state.token

  if (!token && to.name !== 'login') {
    //token不存在，并且当前页面不是登录页，说明当前用户是未登录，应该跳转至登录页
    next({ name: 'login' })
  } else if (token && to.name === 'login') {
    //token存在，并且当前页面是登录页，说明用户登录，此时跳转至首页
    next({ name: 'home' })
  } else if (!checkRouter(to.path)) {
    //如果是不存在的页面，则跳转到首页
    next({ name: 'home' })
  } else {
    next()
  }
})
//全局挂载router
app.use(router)
//全局挂载vuex
app.use(store)
app.mount('#app')
